package edu.task.controller;

import edu.task.common.base.BaseController;
import edu.task.common.constant.UserConstants;
import edu.task.common.result.RestResult;
import edu.task.common.result.TableDataInfo;
import edu.task.model.SysUser;
import edu.task.model.vo.SysUserVO;
import edu.task.service.SysProjectService;
import edu.task.service.SysRoleService;
import edu.task.service.SysTaskService;
import edu.task.service.SysUserService;
import edu.task.utils.StringUtils;
import edu.task.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户表控制层
 */
@RestController
@RequestMapping("/system/user")
@Slf4j
public class SysUserController extends BaseController {
    @Autowired
    SysUserService userService;

    @Autowired
    SysRoleService roleService;

    @Autowired
    SysProjectService projectService;

    @Autowired
    SysTaskService taskService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 显示用户表所有数据
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUserVO user, Pageable page) {
        int pageNum = page.getPageNumber() - 1; //获取当前是第几页
        pageNum = pageNum <= 0 ? 0 : pageNum;
        page = PageRequest.of(pageNum, page.getPageSize()); //获取不带排序的Pageable对象
        return userService.selectUserList(user, page);
    }

    /**
     * 用户新增
     */
    @PostMapping
    public RestResult add(@RequestBody SysUserVO user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return RestResult.error("新增用户" + user.getUserName() + "失败，登录账号已存在");
        }
        user.setCreateBy("system");
        user.setUpdateBy("system");
        boolean flag = userService.insertUser(user);
        return toAjax(flag ? 1 : 0);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public RestResult remove(@PathVariable Long[] userIds){
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 修改新增
     */
    @PutMapping
    public RestResult edit(@Validated @RequestBody SysUserVO user) {
//        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return RestResult.error("修改用户" + user.getUserName() + "失败，手机号码已存在");
//        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return RestResult.error("修改用户" + user.getUserName() + "失败，邮箱账号已存在");
//        }
        user.setUpdateBy("system");
        boolean flag = userService.updateUser(user);
        return toAjax(flag ? 1 : 0);
    }

    /**
     * 根据用户编号获取用户信息和关联角色ID、项目ID、任务ID
     */
    @GetMapping(value = {"/","/{userId}"})
    public RestResult getInfo(@PathVariable(value = "userId",required = false) Long userId){
        RestResult ajax = RestResult.success();
//        ajax.put("roles", roleService.selectRoleAll());
        if (StringUtils.isNotNull(userId)){
            ajax.put(RestResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
            ajax.put("projectIds", projectService.selectProjectListByUserId(userId));
            ajax.put("taskIds", taskService.selectTaskListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 根据用户名查询用户信息
     * @param name
     * @return
     */
    @GetMapping(value = {"/get/{name}"})
    public RestResult index(@PathVariable(value = "name", required = false) String name){
        RestResult ajax = RestResult.success();
        if (StringUtils.isNotNull(name)) {
            ajax.put(RestResult.DATA_TAG, userService.selectUserByName(name));
        }
        return ajax;
    }

    /**
     * 发送邮箱验证码
     * @param
     * @return
     */
    @PostMapping("/sendMsg/{email}")
    public RestResult sendMsg(@PathVariable String email) {
        String subject = "系统验证码";
        if (StringUtils.isNotEmpty(email)) {
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            String context = "尊敬的用户您好!欢迎使用此系统，验证码为: " + code + ",五分钟内有效，请妥善保管!";
//            log.info("code={}", code);

            // 真正地发送邮箱验证码
            userService.sendMsg(email, subject, context);

            //  将随机生成的验证码保存到session中
//            session.setAttribute(phone, code);

            // 验证码由保存到session 优化为 缓存到Redis中，并且设置验证码的有效时间为 5分钟
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);

            return RestResult.success("验证码发送成功，请及时查看!");
        }
        return RestResult.error("验证码发送失败，请重新输入!");
    }

    /**
     * 验证码验证
     * @param map
     * @return
     */
    @PostMapping("/send")
    public RestResult login(@RequestBody Map map) {
        //获取邮箱
        String email = map.get("email").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
//        Object codeInSession = session.getAttribute(phone);

        // 从Redis中获取缓存验证码
        Object codeInSession = redisTemplate.opsForValue().get(email);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够比对成功，说明登录成功
            return RestResult.success("验证正确");
        }
        return RestResult.error("验证失败");
    }

    /**
     * 用户密码更新
     * @param user
     * @return
     */
    @PostMapping("/reset")
    public RestResult reset(@Validated @RequestBody SysUserVO user) {
//        //获取用户名
//        String userName = map.get("userName").toString();

//        //获取密码
//        String password = map.get("password").toString();

        SysUser sysUser = userService.selectUserByName(user.getUserName()).get(0);
        if (sysUser != null) {
            sysUser.setPassword(user.getPassword());
            boolean flag = userService.updatePassword(sysUser);
            return toAjax(flag ? 1 : 0);
        }
        return RestResult.error("验证失败");
    }


    @GetMapping(value = {"/get22"})
    public void sendMailTest() throws Exception {
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        String nick = MimeUtility.encodeText("来消息啦");
        simpleMailMessage.setFrom(String.valueOf(new InternetAddress(nick+ "<"+ "2930742015@qq.com"+ ">")));
        simpleMailMessage.setTo("2930742015@qq.com");
        simpleMailMessage.setSubject("这是一封秘密邮件！！！");
        simpleMailMessage.setText("验证码为：" + checkCode);

        mailSender.send(simpleMailMessage);

        System.out.println("邮件发送成功....");
    }

}
